<template>
    <el-table-column width="40">
        <template #header>
            <el-checkbox
                :modelValue="checkAllCont"
                :indeterminate="!checkAllCont && !checkZeroCont"
                @click.prevent="tapMulti"
                ></el-checkbox
            >
        </template>
       <template #default="{ row }">
            <el-checkbox :modelValue="isCheckedItem(row)" @click.prevent="tapItem(row)"></el-checkbox>
       </template>
    
    </el-table-column>
</template>

<script setup name="CheckColumn">
import {ref,computed} from "vue";
import {ExistInArray,UniquePush,RemoveIfExist} from "hongshu-view";





const props = defineProps({
    list:{  //当前页面的数组
        type:Array,
    },
    modelValue:{    //勾选列表
        type:Array,
    },
    key:{
        type:String,
        default:"id"
    }
});

const emit = defineEmits(["update:modelValue"])


const isCheckedItem = (info)=>{
  let result =  ExistInArray(props.modelValue,info,props.key);
    // console.log(result);
    return result;
};

/**
 * 点击某项
 * @param {*} info 
 */
const tapItem = (info)=>{
    let tagetInfo = {...info};
    let valueCopy = [...JSON.parse(JSON.stringify(props.modelValue))];
    if(ExistInArray(valueCopy,tagetInfo,props.key)){
        RemoveIfExist(valueCopy,tagetInfo,props.key);
    }else{
        
        UniquePush(valueCopy,tagetInfo,props.key);
    };
    emit("update:modelValue",valueCopy);
};

//当前页面是否全钩选
const checkAllCont = computed(()=>{
    if(props.list.length == 0){
        return false;
    }
    let flag = props.list.reduce((pre,item)=>{
       return pre && ExistInArray(props.modelValue,item,props.key)
    },true);

    return flag;
});

//当前页面是否全不勾选
const checkZeroCont = computed(()=>{
    if(props.list.length == 0){
        return true;
    }
    let flag = props.list.reduce((pre,item)=>{
       return pre && !ExistInArray(props.modelValue,item,props.key)
    },true);

    return flag;
});

/**
 * 点击批量
 */
const tapMulti = ()=>{
    let valueCopy = [...JSON.parse(JSON.stringify(props.modelValue))];
    if(checkAllCont.value){
        props.list.forEach((item)=>{
            RemoveIfExist(valueCopy,item,props.key);
        });
    }else{
        props.list.forEach((item)=>{
            UniquePush(valueCopy,item,props.key);
        });
    };
    emit("update:modelValue",valueCopy);
};


</script>

<style lang="less" scoped>

</style>